//
//  HJDataPacketHeader.m
//  Q24141
//
//  Created by lx on 2023/10/16.
//

#import "HJDataPacketHeader.h"
#import "HJDataPacketByteLength.h"
#import "HJDataInputStream.h"



@interface HJDataPacketHeader()
  
@property (nonatomic, assign) uint32_t packageLenght;
@property (nonatomic, assign) uint16_t headerLenght;
@property (nonatomic, assign) uint16_t protocolVersion;
@property (nonatomic, assign) uint32_t operation;
@property (nonatomic, assign) uint64_t seqId;
@property (nonatomic, strong) NSData *data;


@end

@implementation HJDataPacketHeader


- (HJDataPacketHeader * _Nullable )initWithHeaderData:(NSData *)headerData; {
    
    if (headerData.length < 16) return nil;
    
    if (self = [super init]) {
       
        HJDataInputStream *dataInputStream = [[HJDataInputStream alloc] initWithData:headerData];
        
        self.packageLenght = [dataInputStream readInt];
        self.headerLenght = [dataInputStream readShort];
        self.protocolVersion = [dataInputStream readShort];
        self.operation = [dataInputStream readInt];
        self.seqId = [dataInputStream readInt];
    }
    return self;
}

- (HJDataPacketHeader *)initWithBodyData:(nullable NSData *)bodyData seq:(uint64_t)seq operation:(int)operation {
    if (self = [super init]) {
        
        self.headerLenght = 16;
        self.packageLenght = self.headerLenght + (int)bodyData.length;
        
        self.protocolVersion = 1;
        self.operation = operation;
        self.seqId = seq;
        
        NSMutableData *totalHeaderData = [NSMutableData data];
        
        NSData *packageData = [NSData dataByteArrayFromValue:self.packageLenght withByteCount:HJDataPacketByteLength.package];
        NSData *headerData = [NSData dataByteArrayFromValue:self.headerLenght withByteCount:HJDataPacketByteLength.header];
        NSData *protocolData = [NSData dataByteArrayFromValue:self.protocolVersion withByteCount:HJDataPacketByteLength.protocol];
        NSData *operationData = [NSData dataByteArrayFromValue:operation withByteCount:HJDataPacketByteLength.operation];
        NSData *sequenceData = [NSData dataByteArrayFromValue:seq withByteCount:HJDataPacketByteLength.seqId];
        
        [totalHeaderData appendData:packageData];
        [totalHeaderData appendData:headerData];
        [totalHeaderData appendData:protocolData];
        [totalHeaderData appendData:operationData];
        [totalHeaderData appendData:sequenceData];
    
        self.data = totalHeaderData;
    
    }
    return self;
}


- (NSString *)description {
    return [NSString stringWithFormat:@"packageLenght = %u, headerLenght = %u, protocolVersion = %u,  operation = %u, seqId = %lld", _packageLenght, _headerLenght, _protocolVersion, _operation, _seqId];
}



@end
